<template>
    <div class="bg-white h-[64px] border-b border-gray-200 flex items-center justify-between px-4 shadow-sm">
        <!-- 左侧：菜单收缩按钮 -->
        <div class="flex items-center">
            <el-button :icon="isCollapse ? Expand : Fold" circle @click="toggleMenu" class="hover:bg-gray-100" />
        </div>

        <!-- 右侧：操作区域 -->
        <div class="flex items-center gap-3">
            <!-- 全局刷新 -->
            <el-tooltip content="刷新" placement="bottom">
                <el-button :icon="Refresh" circle @click="handleRefresh" class="hover:bg-gray-100" />
            </el-tooltip>

            <!-- 全屏 -->
            <el-tooltip :content="isFullscreen ? '退出全屏' : '全屏'" placement="bottom">
                <el-button :icon="FullScreen" circle @click="toggleFullscreen" class="hover:bg-gray-100" />
            </el-tooltip>

            <!-- 用户信息下拉菜单 -->
            <el-dropdown @command="handleCommand" trigger="click">
                <div
                    class="flex items-center gap-2 cursor-pointer hover:bg-gray-100 rounded-lg px-3 py-2 transition-colors">
                    <el-avatar :size="36" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
                    <span class="text-gray-700 font-medium">{{ userStore.getUsername || 'Admin' }}</span>
                    <el-icon class="text-gray-500">
                        <ArrowDown />
                    </el-icon>
                </div>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="profile" :icon="User">
                            个人信息
                        </el-dropdown-item>
                        <el-dropdown-item command="password" :icon="Lock">
                            修改密码
                        </el-dropdown-item>
                        <el-dropdown-item divided command="logout" :icon="SwitchButton">
                            退出登录
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </div>

        <!-- 个人信息对话框 -->
        <el-dialog v-model="profileDialogVisible" title="个人信息" width="500px" :close-on-click-modal="false">
            <el-form label-width="100px">
                <el-form-item label="用户名">
                    <el-input v-model="profileForm.username" disabled />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="profileDialogVisible = false">关闭</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 修改密码对话框 -->
        <el-dialog v-model="passwordDialogVisible" title="修改密码" width="500px" :close-on-click-modal="false">
            <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="100px">
                <el-form-item label="原密码" prop="oldPassword">
                    <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码" show-password
                        clearable />
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                    <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码（6-20位）"
                        show-password clearable />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码"
                        show-password clearable />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="passwordDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmitPassword" :loading="submitLoading">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/userStore'
import { useTagStore } from '@/stores/tagStore'
import { ElMessage, ElMessageBox } from 'element-plus'
import { updatePassword } from '@/api/user' 
import {
    Fold,
    Expand,
    Refresh,
    FullScreen,
    ArrowDown,
    User,
    Lock,
    SwitchButton
} from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const tagStore = useTagStore()

// 菜单收缩状态
const isCollapse = ref(false)
// 全屏状态
const isFullscreen = ref(false)

// 个人信息对话框
const profileDialogVisible = ref(false)

// 个人信息表单
const profileForm = ref({
    username: ''
})

// 修改密码对话框
const passwordDialogVisible = ref(false)
const passwordFormRef = ref(null)
const submitLoading = ref(false)

// 修改密码表单
const passwordForm = ref({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
})

// 验证确认密码
const validateConfirmPassword = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次输入新密码'))
    } else if (value !== passwordForm.value.newPassword) {
        callback(new Error('两次输入的密码不一致'))
    } else {
        callback()
    }
}

// 表单验证规则
const passwordRules = {
    oldPassword: [
        { required: true, message: '请输入原密码', trigger: 'blur' }
    ],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, validator: validateConfirmPassword, trigger: 'blur' }
    ]
}

// 定义事件
const emit = defineEmits(['toggle-menu'])

// 切换菜单
const toggleMenu = () => {
    isCollapse.value = !isCollapse.value
    emit('toggle-menu', isCollapse.value)
}

// 刷新页面
const handleRefresh = () => {
    location.reload()
}

// 切换全屏
const toggleFullscreen = () => {
    if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen()
        isFullscreen.value = true
    } else {
        if (document.exitFullscreen) {
            document.exitFullscreen()
            isFullscreen.value = false
        }
    }
}

// 监听全屏变化
document.addEventListener('fullscreenchange', () => {
    isFullscreen.value = !!document.fullscreenElement
})

// 处理下拉菜单命令
const handleCommand = (command) => {
    switch (command) {
        case 'profile':
            handleProfile()
            break
        case 'password':
            handlePassword()
            break
        case 'logout':
            handleLogout()
            break
    }
}

// 打开个人信息对话框（只读查看）
const handleProfile = () => {
    profileDialogVisible.value = true
    
    // 从 store 获取用户信息
    const userInfo = userStore.getUserInfo
    profileForm.value = {
        username: userInfo.username || userStore.getUsername || ''
    }
}

// 打开修改密码对话框
const handlePassword = () => {
    passwordDialogVisible.value = true
    // 重置表单
    if (passwordFormRef.value) {
        passwordFormRef.value.resetFields()
    }
    passwordForm.value = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
    }
}

// 提交修改密码
const handleSubmitPassword = async () => {
    if (!passwordFormRef.value) return

    await passwordFormRef.value.validate(async (valid) => {
        if (valid) {
            submitLoading.value = true
            try {
                const data = {
                    username: userStore.getUsername,
                    oldPassword: passwordForm.value.oldPassword,
                    newPassword: passwordForm.value.newPassword
                }

                const res = await updatePassword(data)
                if (res.success) {
                    
                    ElMessage.success('密码修改成功，请重新登录')
                    passwordDialogVisible.value = false
                    submitLoading.value = false
                    // 延迟跳转，让用户看到成功提示
                    setTimeout(() => {
                        userStore.logout()
                        tagStore.clearTags()
                        router.push('/admin/login')
                    }, 1500)
                } else {
                    ElMessage.error(res.message)
                }
            } catch (error) {
                ElMessage.error(error)
            } finally {
                submitLoading.value = false
            }
        } else {
            ElMessage.warning('请填写完整信息')
            return false
        }
    })
}


// 退出登录
const handleLogout = () => {
    ElMessageBox.confirm(
        '确定要退出登录吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            userStore.logout()
            tagStore.clearTags()
            router.push('/admin/login')
            ElMessage.success('退出登录成功')
        })
        .catch(() => {
            // 取消退出
        })
}
</script>

<style scoped>
/* 自定义样式 */
:deep(.el-button.is-circle) {
    border: none;
}
</style>
